#include <android_native_app_glue.h>
#include <android/log.h>
#include <stdio.h>
#include <unistd.h>
#include <locale.h>
#include <sys/types.h>

#define PRG_NAME	"xclock"

void android_main(struct android_app* state)
{
	char *argv[] = {PRG_NAME,"-display",":0"};
	int pipe_out[2], pipe_err[2];
	pid_t pid;

	// Make sure glue isn't stripped.
	app_dummy();

#if 1
	/******************************
     * stdout, stderr redirection *
     ******************************/
	pipe(pipe_out);
	pipe(pipe_err);
	if ((pid = fork()) == -1)
	{
		__android_log_write(ANDROID_LOG_ERROR,PRG_NAME,"fork() failed.\n");
		return;
	}

	if (pid == 0)
	{
		/* child */
		char readBuffer[256];
		FILE *fp_out, *fp_err;
		fd_set set;
		int ret;

		// Close write end
		close(pipe_out[1]);
		close(pipe_err[1]);

		// Open descriptors for fgets
		fp_out = fdopen(pipe_out[0], "r");
		fp_err = fdopen(pipe_err[0], "r");

		// Now wait for stdout, stderr stuff and hand it over to Android log
		while (1)
		{
			FD_ZERO(&set);
			FD_SET(pipe_out[0], &set);
			FD_SET(pipe_err[0], &set);
			if ((ret = select(pipe_err[0]+1, &set, NULL, NULL, NULL)) < 0) break;
			if (FD_ISSET(pipe_out[0], &set))
				if (fgets(readBuffer, sizeof(readBuffer), fp_out))
					__android_log_write(ANDROID_LOG_INFO,PRG_NAME,readBuffer);
				else break;
			if (FD_ISSET(pipe_err[0], &set))
				if (fgets(readBuffer, sizeof(readBuffer), fp_err))
					__android_log_write(ANDROID_LOG_ERROR,PRG_NAME,readBuffer);
				else break;
		}

		fclose(fp_out);
		fclose(fp_err);
		return;
	}

	/* Parent */
	close(STDOUT_FILENO);
	close(pipe_out[0]);
	dup2(pipe_out[1], STDOUT_FILENO);
	close(pipe_out[1]);

	close(STDERR_FILENO);
	close(pipe_err[0]);
	dup2(pipe_err[1], STDERR_FILENO);
	close(pipe_err[1]);
#else
sleep(30);
#endif

	/* Jump to real entry point */
	main(sizeof(argv)/sizeof(argv[0]),argv);
}
